<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>选择服务</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        h1 {
            font-size: 24px;
            color: #333;
            margin-bottom: 30px;
            text-align: center;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }

        .select-btn {
            width: 100%;
            padding: 12px 20px;
            font-size: 16px;
            color: #fff;
            background: #3d8944;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .select-btn:hover {
            background: #2d7a30;
        }

        .select-btn:active {
            background: #1d5a20;
        }

        .result-display {
            margin-top: 30px;
            padding: 20px;
            background: #f8f8f8;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
        }

        .result-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
        }

        .result-item {
            padding: 8px 0;
            font-size: 14px;
            color: #666;
            border-bottom: 1px solid #e8e8e8;
        }

        .result-item:last-child {
            border-bottom: none;
        }

        .result-item label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
            color: #333;
        }

        .result-item span {
            color: #3d8944;
        }

        .empty-text {
            color: #999;
            font-size: 14px;
            text-align: center;
            padding: 20px;
        }

        /* 弹窗样式 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            animation: fadeIn 0.3s;
        }

        .modal-overlay.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        .modal-container {
            position: relative;
            width: 90%;
            max-width: 900px;
            height: 80vh;
            background: #fff;
            border-radius: 12px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            animation: slideUp 0.3s;
        }

        @keyframes slideUp {
            from {
                transform: translateY(50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            background: #fff;
            flex-shrink: 0;
        }

        .modal-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .close-btn {
            width: 32px;
            height: 32px;
            border: none;
            background: #f5f5f5;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }

        .close-btn:hover {
            background: #e0e0e0;
        }

        .close-btn::before {
            content: '✕';
            font-size: 20px;
            color: #666;
        }

        .modal-body {
            flex: 1;
            overflow: hidden;
            position: relative;
        }

        .modal-body iframe {
            width: 100%;
            height: 100%;
            border: none;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
            background: #fff;
            flex-shrink: 0;
        }

        .modal-footer button {
            padding: 10px 30px;
            font-size: 14px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .cancel-btn {
            background: #f5f5f5;
            color: #666;
        }

        .cancel-btn:hover {
            background: #e0e0e0;
        }

        .confirm-btn {
            background: #3d8944;
            color: #fff;
        }

        .confirm-btn:hover {
            background: #2d7a30;
        }

        .confirm-btn:active {
            background: #1d5a20;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .container {
                padding: 20px;
            }

            .modal-container {
                width: 95%;
                height: 85vh;
            }

            h1 {
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>选择服务</h1>
        
        <div class="form-group">
            <label class="form-label">请选择服务项目：</label>
            <button class="select-btn" onclick="openModal()">点击选择服务</button>
        </div>

        <div class="result-display" id="resultDisplay">
            <div class="result-title">选择结果：</div>
            <div class="empty-text">暂未选择服务</div>
        </div>
    </div>

    <!-- 弹窗 -->
    <div class="modal-overlay" id="modalOverlay">
        <div class="modal-container">
            <div class="modal-header">
                <div class="modal-title">选择服务分类</div>
                <button class="close-btn" onclick="closeModal()"></button>
            </div>
            <div class="modal-body">
                <iframe id="chooseIframe" src="" frameborder="0"></iframe>
            </div>
            <div class="modal-footer">
                <button class="cancel-btn" onclick="closeModal()">取消</button>
                <button class="confirm-btn" onclick="confirmSelection()">确定</button>
            </div>
        </div>
    </div>

    <script>
        // 存储选中的服务信息
        let selectedService = null;

        // 从 URL 获取 token 参数
        function getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // 打开弹窗
        function openModal() {
            const token = getUrlParam('token');
            const validate = getUrlParam('validate') || '0';
            
            // 构建 choose.html 的 URL，传递必要的参数
            // let iframeUrl = './choose.html';
            let iframeUrl = 'https://anfine.huasun-healthcare.com/list/choose.html';
            if (token) {
                iframeUrl += `?token=${token}&validate=${validate}`;
            }
            
            const iframe = document.getElementById('chooseIframe');
            iframe.src = iframeUrl;
            
            const overlay = document.getElementById('modalOverlay');
            overlay.classList.add('show');
            
            // 防止背景滚动
            document.body.style.overflow = 'hidden';
        }

        // 关闭弹窗
        function closeModal() {
            const overlay = document.getElementById('modalOverlay');
            overlay.classList.remove('show');
            
            // 恢复背景滚动
            document.body.style.overflow = '';
            
            // 清空 iframe
            setTimeout(() => {
                document.getElementById('chooseIframe').src = '';
            }, 300);
        }

        // 确定选择
        function confirmSelection() {
            const iframe = document.getElementById('chooseIframe');
            
            // 检查 iframe URL 是否跨域
            const iframeUrl = iframe.src;
            const isLocal = iframeUrl.startsWith('./') || 
                           iframeUrl.startsWith(window.location.origin) ||
                           iframeUrl.indexOf('://') === -1;
            
            if (isLocal) {
                // 同域情况：直接访问 DOM
                try {
                    const iframeWindow = iframe.contentWindow;
                    const iframeDocument = iframeWindow.document;
                    
                    // 查找选中的第三级分类按钮
                    const activeLevel3Btn = iframeDocument.querySelector('.level3-btn.active');
                    
                    if (activeLevel3Btn) {
                        const serviceId = activeLevel3Btn.getAttribute('data-id');
                        const serviceName = activeLevel3Btn.textContent.trim();
                        
                        // 保存选中的服务信息
                        selectedService = {
                            id: serviceId,
                            name: serviceName
                        };
                        
                        // 显示选择结果
                        displayResult(selectedService);
                        
                        // 关闭弹窗
                        closeModal();
                    } else {
                        alert('请先选择一个服务分类');
                    }
                } catch (error) {
                    console.error('获取选中信息失败:', error);
                    alert('获取选中信息失败，请重试');
                }
            } else {
                // 跨域情况：使用 postMessage 通信
                try {
                    // 向 iframe 发送消息，请求获取选中的服务信息
                    iframe.contentWindow.postMessage({
                        action: 'getSelectedService'
                    }, '*');
                    
                    // 设置超时提醒
                    setTimeout(() => {
                        if (!selectedService || !selectedService.pendingConfirm) {
                            alert('未收到服务选择信息，请确保已选择服务');
                        }
                    }, 1000);
                } catch (error) {
                    console.error('发送消息失败:', error);
                    alert('跨域通信失败，请联系管理员');
                }
            }
        }

        // 显示选择结果
        function displayResult(service) {
            const resultDisplay = document.getElementById('resultDisplay');
            
            if (!service) {
                resultDisplay.innerHTML = `
                    <div class="result-title">选择结果：</div>
                    <div class="empty-text">暂未选择服务</div>
                `;
                return;
            }
            
            resultDisplay.innerHTML = `
                <div class="result-title">选择结果：</div>
                <div class="result-item">
                    <label>服务ID：</label>
                    <span>${service.id}</span>
                </div>
                <div class="result-item">
                    <label>服务名称：</label>
                    <span>${service.name}</span>
                </div>
            `;
        }

        // 点击遮罩层关闭弹窗
        document.getElementById('modalOverlay').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });

        // ESC 键关闭弹窗
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const overlay = document.getElementById('modalOverlay');
                if (overlay.classList.contains('show')) {
                    closeModal();
                }
            }
        });

        // 监听来自 iframe 的消息（用于跨域通信）
        window.addEventListener('message', function(event) {
            console.log('收到消息:', event.data);
            
            // 安全检查：可以在生产环境中限制 origin
            // if (event.origin !== 'https://anfine.huasun-healthcare.com') return;
            
            if (event.data && event.data.action === 'selectedService') {
                // 接收到选中的服务信息
                const serviceInfo = event.data.data;
                
                if (serviceInfo && serviceInfo.id && serviceInfo.name) {
                    selectedService = {
                        id: serviceInfo.id,
                        name: serviceInfo.name,
                        pendingConfirm: true
                    };
                    
                    // 显示选择结果
                    displayResult(selectedService);
                    
                    // 关闭弹窗
                    closeModal();
                } else {
                    alert('未选择服务或服务信息不完整');
                }
            }
        });

        // 页面加载完成后的初始化
        window.addEventListener('DOMContentLoaded', function() {
            console.log('选择服务页面已加载');
            
            // 检查是否有 token 参数
            const token = getUrlParam('token');
            if (!token) {
                console.warn('URL 中缺少 token 参数，建议添加：?token=xxx');
            }
        });
    </script>
</body>
</html>

